package com.tjp.eight.ui.fragment.tabvideo;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tjp.eight.R;
import com.tjp.eight.utils.BitmapUtils;

import java.util.ArrayList;
import java.util.Formatter;
import java.util.Locale;

import com.tjp.eight.utils.StringUtils;
import com.tjp.eight.views.MyMPViews;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

/**
 * Created by Administrator on 2017/2/14.
 */

public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private ArrayList<VideoItemModel> modelsArray;
    private UpdateCount updateCount;
    private UpdateZanCount updateZanCount;
    private GetOUrl getOUrl;
    private TextView currentTvZan;
    private ShareVideo shareVideo;
    private ImageView currentIvZan;
    private TextView currentTvView;
    public final static int TYPE_VIEWS = 0;
    public final static int TYPE_ZAN = 1;
    private int currentPos = -1;

    public VideoAdapter(Context context) {
        this.context = context;
        modelsArray = new ArrayList<>();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new VideoViewHolder(LayoutInflater.from(context).inflate(R.layout.fragment_video_item, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final int pos = position;
        ((VideoViewHolder) holder).jcVideoPlayerStandard.setUp(modelsArray.get(position).video_link
                , MyMPViews.SCREEN_LAYOUT_NORMAL, modelsArray.get(position).title);
        ((VideoViewHolder) holder).jcVideoPlayerStandard.titleTextView.setText("" + modelsArray.get(position).title);
        final String vid = modelsArray.get(pos).vid;
        ((VideoViewHolder) holder).jcVideoPlayerStandard.setUrlReGet(new MyMPViews.UrlReGet() {
            @Override
            public void getUrl() {
                if (getOUrl != null && modelsArray.get(pos).urlCount < 3) {
                    currentPos = pos;
                    getOUrl.getOUrl(pos, vid);
                }
                modelsArray.get(pos).urlCount++;
            }
        });
        if (currentPos == pos) {
            ((VideoViewHolder) holder).jcVideoPlayerStandard.startVideo();
            currentPos = -1;
        }

        Glide.with(context).
                load(modelsArray.get(position).thumb)
                .placeholder(R.drawable.loading).
                into(((VideoViewHolder) holder).jcVideoPlayerStandard.thumbImageView);
        String times = stringForTime(modelsArray.get(pos).duration);
        ((VideoViewHolder) holder).jcVideoPlayerStandard.tv_duration_tips.setText(times);
        ((VideoViewHolder) holder).tvZanCount.setText("" + StringUtils.toWan(modelsArray.get(position).praise));
        ((VideoViewHolder) holder).tv_play_count.setText("" + StringUtils.toWan(modelsArray.get(position).play_count) + "次播放");
        final TextView c = ((VideoViewHolder) holder).tv_play_count;
        ((VideoViewHolder) holder).jcVideoPlayerStandard.setUpdateEvent(new MyMPViews.UpdateEvent() {
            @Override
            public void updateEvent() {
                if (updateCount != null) {
                    updateCount.update(pos, TYPE_VIEWS, modelsArray.get(position).vid);
                    currentTvView = c;
                }
            }
        });
        final TextView z = ((VideoViewHolder) holder).tvZanCount;
        final ImageView civ = ((VideoViewHolder) holder).iv_video_zan;
        final String vids = modelsArray.get(pos).vid;
        ((VideoViewHolder) holder).iv_video_zan.setImageBitmap(BitmapUtils.getBitmap(context, R.drawable.like_un));
        ((VideoViewHolder) holder).iv_video_zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentIvZan = civ;
                if (updateZanCount != null) {
                    updateZanCount.update(pos, TYPE_ZAN, modelsArray.get(position).vid);
                    currentTvZan = z;
                }
            }
        });
        ((VideoViewHolder) holder).iv_video_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shareVideo != null) {
                    shareVideo.share(vids);
                }
            }
        });
        if (modelsArray.get(pos).if_praise == 1) {
            ((VideoViewHolder) holder).iv_video_zan.setImageBitmap(BitmapUtils.getBitmap(context, R.drawable.like));
            ((VideoViewHolder) holder).iv_video_zan.setClickable(false);
        } else {
            ((VideoViewHolder) holder).iv_video_zan.setImageBitmap(BitmapUtils.getBitmap(context, R.drawable.like_un));
            ((VideoViewHolder) holder).iv_video_zan.setClickable(true);
        }
    }

    @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        if (((VideoViewHolder) holder).jcVideoPlayerStandard.currentState == JCVideoPlayer.CURRENT_STATE_PLAYING) {
            JCVideoPlayer.releaseAllVideos();
        }
    }

    @Override
    public int getItemCount() {
        return modelsArray.size();
    }

    String stringForTime(int timeMs) {
        if (timeMs <= 0 || timeMs >= 24 * 60 * 60) {
            return "00:00";
        }
        int totalSeconds = timeMs;// / 1000;
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;
        StringBuilder stringBuilder = new StringBuilder();
        Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds) + "";
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds) + "";
        }
    }

    public void addData(ArrayList<VideoItemModel> arrayList) {
        if (arrayList == null || arrayList.isEmpty()) return;
        int starPosition = modelsArray.size();
        for (VideoItemModel model : arrayList) {
            modelsArray.add(model);
        }
        notifyItemRangeInserted(starPosition, arrayList.size());
    }

    public void mUrl(int pos, String url) {
        if (pos >= modelsArray.size() || pos < 0) return;
        modelsArray.get(pos).video_link = url;
        notifyItemChanged(pos);
        currentPos = pos;
    }

    public void rdata(ArrayList<VideoItemModel> arrayList) {
        if (arrayList == null || arrayList.isEmpty()) return;
        modelsArray.clear();
        for (VideoItemModel model : arrayList) {
            modelsArray.add(model);
        }
        notifyDataSetChanged();
    }

    public void setGetOUrl(GetOUrl getOUrl) {
        this.getOUrl = getOUrl;
    }

    public void setShareVideo(ShareVideo shareVideo) {
        this.shareVideo = shareVideo;
    }

    public void setUpdateCount(UpdateCount updateCount) {
        this.updateCount = updateCount;
    }

    public void setUpdateZanCount(UpdateZanCount updateZanCount) {
        this.updateZanCount = updateZanCount;
    }

    public void setViewsCount(int count, int pos) {
        modelsArray.get(pos).play_count = modelsArray.get(pos).play_count + 1;
        if (currentTvView != null) {
            currentTvView.setText("" + StringUtils.toWan(modelsArray.get(pos).play_count) + "次播放");
            currentTvView = null;
        }
    }

    public void setZanTvCount(int count, int pos) {
        currentIvZan.setImageBitmap(BitmapUtils.getBitmap(context, R.drawable.like));
        modelsArray.get(pos).praise = modelsArray.get(pos).praise + 1;
        if (currentTvZan != null) {
            currentTvZan.setText("" + StringUtils.toWan(modelsArray.get(pos).praise));
            currentTvZan = null;
        }
    }

    class VideoViewHolder extends RecyclerView.ViewHolder {
        MyMPViews jcVideoPlayerStandard;
        TextView tvZanCount;
        TextView tv_play_count;
        ImageView iv_video_zan;
        ImageView iv_video_share;

        public VideoViewHolder(View view) {
            super(view);
            jcVideoPlayerStandard = (MyMPViews) view.findViewById(R.id.js_video);
            jcVideoPlayerStandard.titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tvZanCount = (TextView) view.findViewById(R.id.tv_video_zan_count);
            tv_play_count = (TextView) view.findViewById(R.id.tv_play_count);
            iv_video_zan = (ImageView) view.findViewById(R.id.iv_video_zan);
            iv_video_share = (ImageView) view.findViewById(R.id.iv_video_share);
        }
    }

    public interface UpdateCount {
        void update(int pos, int type, String vid);
    }

    public interface UpdateZanCount {
        void update(int pos, int type, String vid);
    }

    public interface ShareVideo {
        void share(String vid);
    }

    /**
     * 当视频url无法播放时候重新请求，获取新的url
     */
    public interface GetOUrl {
        void getOUrl(int pos, String vid);
    }
}
